const mongoose = require("mongoose");
const rp = require("request-promise");

const get = async ({ curPage, eachPage }) => {
  const result = {
    curPage: Number(curPage),
    eachPage: Number(eachPage),
    // 总条数
    // 总页数
    total: 0,
    maxPage: 0,
    rows: []
  };
  const schedulesModel = mongoose.model("schedules");
  //    获取总条数
  result.total = await schedulesModel.countDocuments();
  result.maxPage = Math.ceil(result.total / result.eachPage);
  //   操作类型  填充 忽略条数
  result.rows = await schedulesModel.find().populate("movieId").populate("cinemasId").populate("theaterId").skip((result.curPage - 1) * result.eachPage)
    .limit(result.eachPage)
    .sort({
      _id: -1
    })
    //   执行
    .exec();
  return result;
}

// 新增排片信息
const create = async ({ movieId, cinemasId, theaterId, showTime, showDate, price }) => {
  const data = await mongoose.model("schedules").create({ movieId: movieId, cinemasId: cinemasId, theaterId: theaterId, showTime: showTime, showDate: showDate, price: price });
  const _id = data._id;
  const theatersId = data.theaterId;
  const seats = await mongoose.model("seats").find({ theaterId: theatersId });
  // console.log(seats);
  for (let i = 0; i < seats.length; i++) {
    await mongoose.model("seating").create({ schedules: _id, seatId: seats[i]._id, status:0 })
  }
  return data
}

// 删除排片
const deletes = async ({ _id }) => {
  const data = await mongoose.model("schedules").deleteOne({ _id });
  await mongoose.model("seating").deleteMany({ schedules: _id });
  // console.log(data);
  return data
}

// 修改排片
const modify = async ({ _id }, { movieId, cinemasId, theaterId, showTime, price }) => await mongoose.model("schedules").updateOne({ _id: _id }, { movieId: movieId, cinemasId: cinemasId, theaterId: theaterId, showTime: showTime, price: price });

// 根据影院下的排片
const searchone = async (cinemasId) => {
  return await mongoose.model("schedules").find({ cinemasId }).populate("movieId").populate("cinemasId").populate("theaterId").exec()
}

// 根据电影下的排片
const searchmovies = async (movieId) => {
  return await mongoose.model("schedules").find({ movieId }).populate("movieId").populate("cinemasId").populate("theaterId").exec()
}
// 根据Id查排片
const searchid = async (_id) => {
  return await mongoose.model("schedules").find({ _id }).populate("movieId").populate("cinemasId").populate("theaterId").exec()
}
//通过放映厅查找座位
const Seats = async ({schedules}) => {
  const data = await mongoose.model("seating").find({schedules}).populate("seatId").populate("schedules");
  // console.log(data);
  return data;
}
module.exports = { get, deletes, modify, create, searchone, searchmovies, searchid,Seats };

